#coding=utf-8
#!/usr/bin/python

from glob import glob
#pip install Pillow
from PIL import Image, ImageDraw, ImageFont
import os
import math

#原始图片目录
SORUCE_DIR = '/Users/xxxx'
#处理后图片目录
TARGET_DIR= 'RS'
#图片筛选条件
THRESHOLD = 100000  #100kb
#图片最大宽/高
NEW_W_H = 800
#是否开启水印 0不开启 1开启
WAHTER_MARK = 0  

FONT_FAMILY = 'C:\\Windows\\Fonts\\constan.ttf'

def add_text_to_image(image, text, font_size, font_family=FONT_FAMILY):
    width, height = image.size
    #相当于将图片转换为可以绘制的画布
    img_draw = ImageDraw.Draw(image)
    #创建字体画笔
    Font = ImageFont.truetype(font_family, font_size)  
    #获取文字尺寸
    textW,textH = Font.getsize(text)   
    #将文字写在空白图像正中间      
    pointX = width - textW - textH / 2
    pointY = height - textH - textH / 2
    img_draw.text([pointX, pointY], text, fill=(255, 255, 255, 100), font = Font)


def resize_images(source_dir, target_dir, threshold, new_w_or_h):
    #读取目录下所有文件
    filenames = glob('{}/*'.format(source_dir))
    #判断输出目录
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    #遍历处理
    for filename in filenames:
        filesize = os.path.getsize(filename)
        #比较筛选
        if filesize >= threshold:
            with Image.open(filename) as im:
                width, height = im.size
                #判断图片方向（横/竖）
                if width >= height:
                    new_width = new_w_or_h
                    new_height = int(new_width * height * 1.0 / width)
                else:
                    new_height = new_w_or_h
                    new_width = int(new_height * width * 1.0 / height)
                resized_im = im.resize((new_width, new_height))
                #判断是否添加水印
                if WAHTER_MARK != 0:
                    add_text_to_image(resized_im, "dp2px.com", int(new_w_or_h / 30))
                #保存到输出目录
                output_filename = filename.replace(source_dir, target_dir)
                resized_im.save(output_filename)
    print('图片处理完成!')

#调用处理方法处理图片
resize_images(SORUCE_DIR, TARGET_DIR, THRESHOLD, NEW_W_H)